package org.imlinker.list;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JList;

import org.imlinker.buddy.BuddyList;
import org.imlinker.core.Core;
import org.imlinker.message.MessageList;
import org.imlinker.plugin.PluginList;
import org.imlinker.plugin.PluginManager;

import org.jivesoftware.smack.XMPPConnection;

/**
 * 管理列表在MaiWindow中的显示，包括添加删除ListItem.
 */
public class ListManager extends MouseAdapter {

	public ListManager(final XMPPConnection connection,
			final PluginManager pluginManager, final Core core) {

		// 初始化三个List
		messageList = new MessageList(core);

		buddyList = new BuddyList(connection, messageList);

		pluginList = new PluginList();
		pluginManager.setList(pluginList);

	}

	public void initialLists(JList messageList2, JList buddyList2,
			JList pluginList2) {
		CellRender cellRender = new CellRender();

		messageList2.setModel(messageList);
		messageList2.setCellRenderer(cellRender);
		messageList2.addMouseListener(this);

		buddyList2.setModel(buddyList);
		buddyList2.setCellRenderer(new BuddListCellRender());
		buddyList2.addMouseListener(this);

		pluginList2.setModel(pluginList);
		pluginList2.setCellRenderer(cellRender);
		pluginList2.addMouseListener(this);
	}

	@Override
	public void mouseClicked(MouseEvent e) {
		JList sourceList = (JList) e.getSource();
		int index = sourceList.locationToIndex(e.getPoint());
		if (index == -1) {
			return;
		}

		ListModel model = (ListModel) sourceList.getModel();
		ListItem item = (ListItem) model.getElementAt(index);

		// 排除没有选中元素的情况。
		if (item == null) {
			return;
		}

		// 双击的情况
		if (e.getClickCount() == 2) {
			model.openItem(item);
		}

	}

	public boolean openFirstMessage() {
		if (messageList.isEmpty()) {
			return false;
		}

		return messageList.openFirstMessage();
	}

	private MessageList messageList;

	private BuddyList buddyList;

	private PluginList pluginList;

}
